﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ERP系统首页</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .dashboard-container {
            padding: 15px;
        }
        .time-filter {
            margin-bottom: 20px;
        }
        .time-filter .layui-btn {
            margin-right: 10px;
        }
        .chart-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,.08);
            height: 400px;
        }
        .chart-row {
            display: flex;
            margin: 0 -10px;
        }
        .chart-col {
            flex: 1;
            padding: 0 10px;
        }
        .chart {
            width: 100%;
            height: 100%;
            min-height: 300px;
        }
        .production-progress {
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,.08);
        }
        .active {
            background-color: #009688 !important;
            color: #fff !important;
        }
        .loading {
            text-align: center;
            padding: 20px;
            font-size: 14px;
            color: #999;
        }
        .layui-table {
            margin-top: 0;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <!-- 趋势图 -->
        <div class="chart-container">
            <div id="trendChart" class="chart"></div>
        </div>

        <!-- 图表行1 -->
        <div class="chart-row">
            <div class="chart-col">
                <div class="chart-container">
                    <div id="radarChart" class="chart"></div>
                </div>
            </div>
            <div class="chart-col">
                <div class="chart-container">
                    <div id="pieChart" class="chart"></div>
                </div>
            </div>
            <div class="chart-col">
                <div class="chart-container">
                    <div id="barChart" class="chart"></div>
                </div>
            </div>
        </div>

        <!-- 库存数据表格 -->
        <div class="production-progress">
            <table class="layui-table" lay-skin="line">
                <thead>
                    <tr>
                        <th>产品物料编码</th>
                        <th>产品物料名称</th>
                        <th>规格型号</th>
                        <th>在库数量</th>
                        <th>单位</th>
                        <th>入库批次号</th>
                        <th>仓库</th>
                        <th>库区</th>
                        <th>库位</th>
                        <th>供应商编号</th>
                        <th>供应商名称</th>
                        <th>生产工单</th>
                        <th>入库日期</th>
                        <th>库存有效期</th>
                    </tr>
                </thead>
                <tbody id="inventoryTable">
                    <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 引入JS库 -->
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>

    <script>
        // 确保ECharts加载完成
        function waitForECharts(callback) {
            if (typeof echarts !== 'undefined') {
                callback();
            } else {
                setTimeout(function() {
                    waitForECharts(callback);
                }, 100);
            }
        }

        layui.use(['layer', 'element', 'table'], function() {
            var layer = layui.layer;
            var element = layui.element;
            var table = layui.table;
            
            // 等待ECharts加载完成后初始化
            waitForECharts(function() {
                loadInventoryData();
                
                // 绑定时间筛选事件
                $('.time-filter .layui-btn').click(function() {
                    $(this).addClass('active').siblings().removeClass('active');
                    var type = $(this).data('type');
                    loadInventoryData(type);
                });

                // 触发默认选中本周
                $('.time-filter .layui-btn[data-type="week"]').click();
            });
        });

        // 加载库存数据
        function loadInventoryData(timeType) {
            // 显示加载中
            layer.load(2);
            
            // 调用后端接口获取数据
            $.ajax({
                url: '/HomePages/GetInventory',
                type: 'GET',
                success: function(response) {
                    console.log('Raw response:', response);
                    // 处理 ABP 响应格式
                    let data = response;
                    if (response && response.result) {
                        data = response.result;
                    }
                    if (Array.isArray(data)) {
                        updateInventoryTable(data);
                        updateCharts(data);
                    } else {
                        layer.msg('数据格式不正确');
                        console.error('Invalid data format:', data);
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('请求失败：' + error);
                },
                complete: function() {
                    layer.closeAll('loading');
                }
            });
        }

        // 更新库存表格
        function updateInventoryTable(data) {
            console.log('Processing data:', data);
            var html = '';
            data.forEach(function(item) {
                console.log('Processing item:', item);
                
                // 处理属性名，返回空字符串而不是'-'
                const getValue = (key) => {
                    const value = item[key];
                    if (value === undefined || value === null) return '';
                    
                    // 处理日期字段
                    if (key === 'storageDate' || key === 'storagevalidity') {
                        if (value && value.includes('T')) {
                            return value.split('T')[0];
                        }
                    }
                    return value;
                };
                
                html += `
                    <tr>
                        <td>${getValue('productItem')}</td>
                        <td>${getValue('productName')}</td>
                        <td>${getValue('specs')}</td>
                        <td>${getValue('galleryNumber')}</td>
                        <td>${getValue('unit')}</td>
                        <td>${getValue('storage')}</td>
                        <td>${getValue('warehouse')}</td>
                        <td>${getValue('reservoirArea')}</td>
                        <td>${getValue('binLocation')}</td>
                        <td>${getValue('supplierNumber')}</td>
                        <td>${getValue('supplierName')}</td>
                        <td>${getValue('produceTickets')}</td>
                        <td>${getValue('storageDate')}</td>
                        <td>${getValue('storagevalidity')}</td>
                    </tr>
                `;
            });
            $('#inventoryTable').html(html);
        }

        // 更新图表
        function updateCharts(data) {
            try {
                // 趋势图数据处理
                var dates = [...new Set(data.map(item => {
                    const date = item.storageDate;
                    return date ? date.split('T')[0] : null;
                }).filter(date => date !== null))].sort();

                var quantities = dates.map(date => {
                    return data
                        .filter(item => item.storageDate && item.storageDate.split('T')[0] === date)
                        .reduce((sum, item) => sum + (Number(item.galleryNumber) || 0), 0);
                });

                // 更新趋势图
                var trendChart = echarts.init(document.getElementById('trendChart'));
                trendChart.setOption({
                    title: { text: '入库数量趋势' },
                    tooltip: { trigger: 'axis' },
                    xAxis: { 
                        type: 'category', 
                        data: dates,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        name: '入库数量',
                        type: 'line',
                        smooth: true,
                        data: quantities,
                        itemStyle: { color: '#1ABC9C' }
                    }]
                });

                // 更新雷达图
                var radarChart = echarts.init(document.getElementById('radarChart'));
                radarChart.setOption({
                    title: { text: '部门预算分析' },
                    tooltip: { trigger: 'item' },
                    legend: {
                        data: ['预算分配', '预期支出', '实际支出']
                    },
                    radar: {
                        indicator: [
                            { name: '销售', max: 100 },
                            { name: '市场营销', max: 100 },
                            { name: '研发', max: 100 },
                            { name: '客户支持', max: 100 },
                            { name: '信息技术', max: 100 },
                            { name: '行政管理', max: 100 }
                        ]
                    },
                    series: [{
                        name: '预算 vs 支出',
                        type: 'radar',
                        data: [
                            {
                                value: [80, 70, 90, 85, 75, 70],
                                name: '预算分配',
                                itemStyle: { color: '#5FB878' }
                            },
                            {
                                value: [85, 80, 95, 90, 85, 75],
                                name: '预期支出',
                                itemStyle: { color: '#A095FF' }
                            },
                            {
                                value: [75, 65, 85, 80, 70, 65],
                                name: '实际支出',
                                itemStyle: { color: '#FF9668' }
                            }
                        ]
                    }]
                });

                // 按仓库统计数据
                var warehouseStats = {};
                data.forEach(item => {
                    if (!warehouseStats[item.warehouse]) {
                        warehouseStats[item.warehouse] = 0;
                    }
                    warehouseStats[item.warehouse] += Number(item.galleryNumber) || 0;
                });

                // 更新饼图
                var pieChart = echarts.init(document.getElementById('pieChart'));
                pieChart.setOption({
                    title: { text: '仓库库存分布' },
                    tooltip: { trigger: 'item' },
                    series: [{
                        type: 'pie',
                        radius: '60%',
                        data: Object.entries(warehouseStats).map(([name, value]) => ({
                            name: name || '未知仓库',
                            value: value
                        }))
                    }]
                });

                // 按物料类型统计
                var materialStats = {};
                data.forEach(item => {
                    if (!materialStats[item.productName]) {
                        materialStats[item.productName] = 0;
                    }
                    materialStats[item.productName] += Number(item.galleryNumber) || 0;
                });

                // 更新柱状图
                var barChart = echarts.init(document.getElementById('barChart'));
                var materialNames = Object.keys(materialStats);
                var materialValues = Object.values(materialStats);
                barChart.setOption({
                    title: { text: '物料库存统计' },
                    tooltip: { trigger: 'axis' },
                    xAxis: {
                        type: 'category',
                        data: materialNames,
                        axisLabel: { interval: 0, rotate: 45 }
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        name: '库存数量',
                        type: 'bar',
                        data: materialValues
                    }]
                });

                // 移除加载提示
                $('.loading').remove();

                // 窗口大小改变时重绘图表
                window.addEventListener('resize', function() {
                    trendChart.resize();
                    pieChart.resize();
                    barChart.resize();
                });
            } catch (e) {
                console.error('更新图表时出错：', e);
                layer.msg('图表更新失败');
            }
        }
    </script>
</body>
</html>
